/**
 * Created with JetBrains WebStorm.
 * User: ab
 * Date: 14-6-17
 * Time: 下午3:23
 * To change this template use File | Settings | File Templates.
 */
//记录在线用户
var userList={};

//记录IP
var ipList={};

//WebSocket连接监听
exports.createCon = function (socket, io) {
    socket.emit('open');

// 打印连接信息
    var address = socket.handshake.address;
    console.log("New connection from " + address.address + ":" + address.port);


    // 构造客户端对象
    var client = {
        socket:socket,
        name:false
    }

    // 对message事件的监听
    socket.on('message', function(msg){
        var obj = {time:getTime()};


        // 判断是不是第一次连接，消息为用户名称
        if(!client.name){
            client.name = msg;
            obj['text']=msg;
            obj['author']='System';
            obj['type']='welcome';
            console.log(client.name + ' login');

            var usertxt=client.name;
            //纪录用户和ip信息，用于房间用户筛选，局部通讯
            if (!userList[usertxt]) {
                userList[usertxt] = 1;
            } else {
                userList[usertxt] ++;
            }
            ipList[socket.handshake.address.address]=usertxt;

            //返回欢迎语
            socket.emit('system',obj);
            //广播新用户已登陆
            socket.broadcast.emit('system',obj);

            var objusr = {time:getTime()};
            objusr['text']=userList;
            objusr['author']='System';
            objusr['type']='userConnected';

            //更新用户列表
            io.sockets.emit('system',objusr);
        }else{

            //如果不是第一次的连接，正常的聊天消息
            obj['text']=msg;
            obj['author']=client.name;
            obj['type']='message';
            console.log(client.name + ' say: ' + msg);

            var arr=msg.split("@");
            //将消息用@符号进行分割，筛选出关联的在线用户
            if(arr.length<3 || arr[0]!="")
            {
                // 返回消息（可以省略）
                socket.emit('message',obj);
                // 广播向其他用户发消息
                socket.broadcast.emit('message',obj);
            }
            else
            {
                var flag=0;
                //根据用户名称找到用户对应ip地址，再通过ip地址找到对应的socket连接，将@关联的用户socket加入到一个room中
                io.sockets.clients().forEach(function (socket) {
                    for(ip in ipList)
                    {
                        for(i=0;i<arr.length;i++)
                        {
                            if(ipList[ip]==arr[i] && ip==socket.handshake.address.address)
                            {
                                //加入到指定房间
                                socket.join('someUsers');
                                flag++;
                            }
                        }
                    }
                });
                if(flag==0)
                {
                    socket.join('me');
                    obj['text']="请核实您关联的用户名！";
                    obj['author']='系统';
                    io.sockets.in('me').emit('message', obj);
                }
                else
                {
                    obj['text']=arr[arr.length-1];
//将消息发送给加入该房间的用户
                    io.sockets.in('someUsers').emit('message', obj);
                }
            }

        }
    });

    //监听出退事件
    socket.on('disconnect', function () {
        var obj = {
            time:getTime(),
            color:client.color,
            author:'System',
            text:client.name,
            type:'disconnect'
        };
        var userName=client.name;

        if (userList[userName]) {
            userList[userName] --;
            if (userList[userName] == 0) {
                delete userList[userName];
            }
        }

        for(ip in ipList)
        {
            if (ipList[ip]==client.name)
            {

                delete ipList[ip];
            }

            console.log(ip);
        }

        // 广播用户已退出
        socket.broadcast.emit('system',obj);
        console.log(client.name + 'Disconnect');


        var objusr = {time:getTime()};

        objusr['text']=userList;
        objusr['author']='System';
        objusr['type']='userConnected';


        socket.broadcast.emit('system',objusr);
    });
}